package com.yksj.healthtalk.ui.friend;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshGridView;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.yksj.healthtalk.adapter.FriendAdapter;
import com.yksj.healthtalk.adapter.FriendAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.FriendAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.adapter.FriendFindGridViewAdapter;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.RootFragment;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.setting.PersonalInformationActivity;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.PersonInfoUtil;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * @author Administrator 病友社区
 */
public class FriendMainActivity extends RootFragment implements
		View.OnClickListener, OnItemClickListener,
		onClickFriendAttentionListener, onClickFriendHeadListener,
		FriendHttpListener{

	private double distance;// 附近的距离
	private PullToRefreshListView mPullToRefreshListView;
	private ListView mFriendList;
	private FriendAdapter mFriendListAdapter;
	private FriendFindGridViewAdapter mFriendGridAdapter;
	private View view;
	private LinearLayout content;
	private CustomerInfoEntity mCustomerInfoEntity;
	private ArrayList<CustomerInfoEntity> arrayList;
	private GridView mGridView;
	private int SOURCETYPE;// 0全部 1最新 2活跃 3附近
	private String DEFAUTPAGEMARK = "-100000";
	private String pageMark = DEFAUTPAGEMARK;// 分页的标记
	private IntentFilter filter;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private AppData mAppData;
	private PullToRefreshGridView mPullToRefreshGridView;
	private boolean isShowGrid = false;// 表示列表反之网格
	private CheckBox isCheckedBox;// 现在选中的条目
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				
				LodingFragmentDialog.dismiss(getFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getActivity(), R.string.groupNewFail);
				} else if (result.equals("-1")) {
					ToastUtil.showShort(getActivity(),R.string.against__blacklist_operations);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(getActivity(), cacheCustomerInfoEntity, mAppData);
					mFriendListAdapter.notifyDataSetChanged();
				}
				
			} else if (action.equals(MessagePushService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					if (isShowGrid) {
						mFriendGridAdapter.notifyDataSetChanged();
					} else {
						mFriendListAdapter.notifyDataSetChanged();
					}
				}
			}else if(CoreService.ACTION_COMMONT_CONTENT.equals(intent.getAction())){
				DoubleBtnFragmentDialog.showDefault(getChildFragmentManager(),  "亲，您的好评是对我们最大的鼓励~", "下次吧", "鼓励一下",new OnDilaogClickListener() {
					@Override
					public void onDismiss(DialogFragment fragment) {
						SharePreUtils.updateCommentGoodDay();
					}
					@Override
					public void onClick(DialogFragment fragment, View v) {
						SharePreUtils.updateCommentGood();
						SystemUtils.commentGood(getActivity());
					}
				});
			}
		}
	};
	
	public void onCreate(Bundle savedInstanceState) {
		if (savedInstanceState != null) {
			mCustomerInfoEntity  =  savedInstanceState.getParcelable("mCustomerInfoEntity");
			SOURCETYPE = savedInstanceState.getInt("SOURCETYPE");
		}
		super.onCreate(savedInstanceState);
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mAppData = HTalkApplication.getAppData();
		view = inflater.inflate(R.layout.friend_main_layout, container, false);
		initWidget(view);
		initData(view);
		isShowGrid = false;
		getFriends(activeCheckBtn);
		return view;
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt("SOURCETYPE", SOURCETYPE);
		outState.putParcelable("mCustomerInfoEntity", mCustomerInfoEntity);
		super.onSaveInstanceState(outState);
	}

	private void initData(View v) {
		mCustomerInfoEntity = new CustomerInfoEntity();
		cacheCustomerInfoEntity = new CustomerInfoEntity();
		mFriendList = mPullToRefreshListView.getRefreshableView();
		mGridView = mPullToRefreshGridView.getRefreshableView();

		// setListOrGridAdapter();
		arrayList = new ArrayList<CustomerInfoEntity>();
		mFriendListAdapter = new FriendAdapter(getActivity(), arrayList);
		// 设置列表中元素的监听事件
		mFriendListAdapter.setonClickFriendHeadListener(FriendMainActivity.this);
		mFriendListAdapter.setonClickFriendAttentionListener(FriendMainActivity.this);
		mFriendList.setAdapter(mFriendListAdapter);
		mFriendList.setOnItemClickListener(this);
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

					@Override
					public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
						pageMark = mFriendListAdapter.getPageMark(true);
						searchByFlag(pageMark);
					}

					@Override
					public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
						searchByFlag(pageMark);
					}
				});
		mPullToRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {

					@Override
					public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
						pageMark = mFriendGridAdapter.getPageMark(true);
						searchByFlag(pageMark);
					}

					@Override
					public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
						searchByFlag(pageMark);
					}
				});
	}

	/**
	 * 初始化控件
	 */
	private void initWidget(View v) {
		initTitleView(v);
		mPullToRefreshListView = (PullToRefreshListView) v.findViewById(R.id.hall);
		mPullToRefreshGridView = (PullToRefreshGridView) v.findViewById(R.id.gv);
		content = (LinearLayout) v.findViewById(android.R.id.content);
		allCheckBtn = (CheckBox) view.findViewById(R.id.all_rb);
		activeCheckBtn = (CheckBox) view.findViewById(R.id.active_rb);
		recentlyCheckBtn = (CheckBox) view.findViewById(R.id.recently_rb);
		nearbyBtn = (CheckBox) view.findViewById(R.id.nearby_rb);
		view.findViewById(R.id.top_line).setVisibility(View.GONE);
		// 设置监听
		allCheckBtn.setOnClickListener(this);
		activeCheckBtn.setOnClickListener(this);
		recentlyCheckBtn.setOnClickListener(this);
		nearbyBtn.setOnClickListener(this);
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn2.setBackgroundResource(R.drawable.icon_grids);
		titleRightBtn.setBackgroundResource(R.drawable.icon_search_press);
		titleTextV.setText("病友");
	}

	@Override
	public void onClick(View arg0) {
		// 网格点击头像
		if (arg0.getTag() != null && arg0.getTag() instanceof Integer) {
			int position = (Integer) arg0.getTag();
			FriendHttpUtil.onItemClick(getActivity(), arrayList.get(position));
			return;
		}
		switch (arg0.getId()) {
		case R.id.title_back:
			onBackPressed(arg0);
			break;
		// 切换视图
		case R.id.title_right2:
			if (mFriendGridAdapter != null) {
				if (SOURCETYPE == 3) {
					mFriendGridAdapter.setIsNearBy(true);
				} else {
					mFriendGridAdapter.setIsNearBy(false);
				}
			}
			changeVisibleView();
			break;
		// 按照昵称和多美号查找
		case R.id.title_right:
			Intent intent = new Intent();
			intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
			intent.putExtra("search_type", 1);
			intent.setClass(getActivity(), FriendSearchMainActivity.class);
			startActivityForResult(intent, 0);
			/*Intent intent = new Intent(getActivity(), MyWalletMainActivity.class);
			startActivity(intent);*/
			break;
		case R.id.all_rb:
		case R.id.active_rb:
		case R.id.recently_rb:
		case R.id.nearby_rb:
			getFriends(arg0);
			break;
		}
	}

	private void getFriends(View arg0) {
		pageMark = DEFAUTPAGEMARK;
		if (mCustomerInfoEntity == null) {
			mCustomerInfoEntity = new CustomerInfoEntity();
		}
		mCustomerInfoEntity.setId(SmartFoxClient.getLoginUserId());
		mCustomerInfoEntity.setFlag(pageMark);
		arrayList.clear();
		if (isShowGrid) {
			mFriendGridAdapter.notifyDataSetChanged();
			mPullToRefreshGridView.setRefreshing();
		} else {
			mFriendListAdapter.notifyDataSetChanged();
			mPullToRefreshListView.setRefreshing();
		}
		switch (arg0.getId()) {
		// 全部
		case R.id.all_rb:
			// checkId(allCheckBtn);
			SOURCETYPE = 0;
			break;
		// 活跃
		case R.id.active_rb:
			// checkId(activeCheckBtn);
			SOURCETYPE = 2;
			break;
		// 最新
		case R.id.recently_rb:
			// checkId(recentlyCheckBtn);
			SOURCETYPE = 1;
			break;
		// 附近
		case R.id.nearby_rb:
			// checkId(nearbyBtn);
			SOURCETYPE = 3;
			break;
		}
		checkId((CheckBox) arg0);
		// 附近显示距离
		if (mFriendGridAdapter != null) {
			if (SOURCETYPE == 3) {
				mFriendGridAdapter.setIsNearBy(true);
			} else {
				mFriendGridAdapter.setIsNearBy(false);
			}
		}
		if (mFriendListAdapter != null) {
			mFriendListAdapter.setSOURCETYPE(SOURCETYPE);
		}
		if (SOURCETYPE != 3) {
			FriendHttpUtil.getFriends(mCustomerInfoEntity, SOURCETYPE,FriendMainActivity.this);
		} else {
			onRequestLocation();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			position = position - 1;
			CustomerInfoEntity entity = arrayList.get(position);
			if (entity.isDoctor()) {
				onClickFriendHead(entity, position);
			}else {
				FriendHttpUtil.onItemClick(getActivity(), entity);
			}
		} catch (Exception e) {
			
		}

	}

	// 点击头像
	@Override
	public void onClickFriendHead(CustomerInfoEntity entity, final int positon) {
		if (SmartFoxClient.getLoginUserId().equals(entity.getId())) {
			Intent intent = new Intent();
			intent.setClass(getActivity(), PersonalInformationActivity.class);
			startActivity(intent);
		} else if (entity.isDoctor()) {
			Intent intent = new Intent(getActivity(), DoctorMainActivity.class);
			intent.putExtra("id", entity.getId());
			intent.putExtra("positon", positon);
			intent.putExtra("type", "1");
			startActivityForResult(intent, 0);
		} else {
			Intent intent = new Intent();
			intent.setClass(getActivity(), FriendInformUI.class);
			intent.putExtra("id", entity.getId());
			intent.putExtra("positon", positon);
			// 记录好友之间的距离,返回全数据时距离都0
			distance = entity.getDistance();
			startActivityForResult(intent, 0);
		}
	}

	// 点击后面是否关注按钮
	// 0 无关系 1 我关注的 2 黑名单
	@Override
	public void onClickFriendAttention(int attentioned,
			CustomerInfoEntity entity, int positon) {
		cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(getActivity(), null, entity);
	}

	/**
	 * 网格和列表之间的切换
	 */
	private void changeVisibleView() {
		content.removeAllViews();
		if (!isShowGrid) {
			// 主界面列表
			isShowGrid = true;
			mPullToRefreshGridView.onRefreshComplete();
			content.addView(mPullToRefreshGridView);
			if (mFriendGridAdapter == null) {
				mFriendGridAdapter = new FriendFindGridViewAdapter(getActivity(), arrayList, this);
				if (SOURCETYPE == 3) {
					mFriendGridAdapter.setIsNearBy(true);
				} else {
					mFriendGridAdapter.setIsNearBy(false);
				}
				mGridView.setAdapter(mFriendGridAdapter);
			} else {
				mFriendGridAdapter.notifyDataSetChanged();
			}
			// 列表和网格切换
			titleRightBtn2.setBackgroundResource(R.drawable.icon_list);
		} else {
			isShowGrid = false;
			mPullToRefreshListView.onRefreshComplete();
			content.addView(mPullToRefreshListView);
			if (mFriendListAdapter == null) {
				mFriendListAdapter = new FriendAdapter(getActivity(), arrayList);
				// 设置列表中元素的监听事件
				mFriendListAdapter.setonClickFriendHeadListener(this);
				mFriendListAdapter.setonClickFriendAttentionListener(this);
				mFriendList.setAdapter(mFriendListAdapter);
			} else {
				mFriendListAdapter.notifyDataSetChanged();
			}
			titleRightBtn2.setBackgroundResource(R.drawable.icon_grids);
		}
	}

	@Override
	public void onStop() {
		getActivity().unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public void onStart() {
		filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(CoreService.ACTION_COMMONT_CONTENT);
		getActivity().registerReceiver(receiver, filter);
		super.onStart();
	}

	@Override
	public void onDetach() {
		super.onDetach();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void responseSuccess(int type, int sourceType,
			final ArrayList<CustomerInfoEntity> c) {
		if (SOURCETYPE == sourceType) {
			boolean isFristPage = false;
			if (pageMark.equals("-100000")) {
				arrayList.clear();
			}
			arrayList.addAll(c);
			notifyDataSetChanged(isShowGrid, isFristPage);
		} else {
			mPullToRefreshListView.onRefreshComplete();
			mPullToRefreshGridView.onRefreshComplete();
		}
	}

	public void notifyDataSetChanged(boolean isShowGrid, boolean isFristPage) {
		if (isShowGrid) {
			mFriendGridAdapter.notifyDataSetChanged();
			if (pageMark.equals(DEFAUTPAGEMARK)) {
				mGridView.setSelection(0);
			}
			pageMark = mFriendGridAdapter.getPageMark(isFristPage);
			mPullToRefreshGridView.onRefreshComplete();
		} else {
			mFriendListAdapter.notifyDataSetChanged();
			if (pageMark.equals(DEFAUTPAGEMARK)) {
				mFriendList.setSelection(0);
			}
			pageMark = mFriendListAdapter.getPageMark(isFristPage);
			mPullToRefreshListView.onRefreshComplete();
		}
	}

	@Override
	public void responseError(int type, int sourceType, final String content) {
		if (isShowGrid) {
			mPullToRefreshGridView.onRefreshComplete();
		} else {
			mPullToRefreshListView.onRefreshComplete();
		}
		LodingFragmentDialog.dismiss(getFragmentManager());
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0 && resultCode == 0) {
			if (data != null && data.hasExtra("mFriendInformUI")) {
				if ((Integer) data.getExtras().get("position") != -1) {
					CustomerInfoEntity entity = (CustomerInfoEntity) data
							.getExtras().get("mFriendInformUI");
					if (distance != 0) {
						entity.setDistance(distance);
					}
					arrayList.set((Integer) data.getExtras().get("position"),entity);
					mFriendListAdapter.notifyDataSetChanged();
				}
			} else {
				pageMark = DEFAUTPAGEMARK;
				if (data != null && data.hasExtra("mCustomerInfoEntity")) {
					mCustomerInfoEntity = data.getParcelableExtra("mCustomerInfoEntity");
					mCustomerInfoEntity.setFlag(pageMark);
					checkId(allCheckBtn); 
					getFriends(isCheckedBox);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onDestroy() {
		if (mLocationClient != null && mLocationClient.isStarted()) {
			mLocationClient.stop();
		}
		mLocationClient = null;
		super.onDestroy();
	};

	LocationClient mLocationClient;// 获取位置
	private CheckBox allCheckBtn;
	private CheckBox activeCheckBtn;
	private CheckBox recentlyCheckBtn;
	private CheckBox nearbyBtn;

	private void onRequestLocation() {
		if (mLocationClient == null) {
			mLocationClient = new LocationClient(getActivity()
					.getApplicationContext());
			mLocationClient.registerLocationListener(new BDLocationListener() {
				@Override
				public void onReceivePoi(BDLocation db) {
				}

				@Override
				public void onReceiveLocation(BDLocation db) {
					if (db != null) {
						mCustomerInfoEntity.setLatitude(String.valueOf(db
								.getLatitude()));
						mCustomerInfoEntity.setLongitude(String.valueOf(db
								.getLongitude()));
						FriendHttpUtil.getFriends(mCustomerInfoEntity, 3,
								FriendMainActivity.this);
					} else {
						ToastUtil.showShort(getActivity(), "没有获取到经纬度");
					}
					if (mLocationClient != null) {
						mLocationClient.unRegisterLocationListener(this);
						mLocationClient.stop();
						mLocationClient = null;
					}
				}
			});
			LocationClientOption clientOption = new LocationClientOption();
			clientOption.setOpenGps(true);
			clientOption.setCoorType("gps");
			clientOption.setPoiNumber(3);
			clientOption.setAddrType("detail");
			clientOption.setServiceName("com.baidu.location.service_v3.3");
			clientOption.setPoiExtraInfo(true);
			clientOption.setPriority(LocationClientOption.NetWorkFirst);
			clientOption.disableCache(true);
			clientOption.setPoiDistance(1000);
			clientOption.setScanSpan(6000);
			mLocationClient.setLocOption(clientOption);
		}
		mLocationClient.start();
		mLocationClient.requestLocation();
	}

	/**
	 * 根据标记搜索相应的页数
	 * 
	 * @param Flag
	 */
	private void searchByFlag(String Flag) {
		mCustomerInfoEntity.setFlag(Flag);
		FriendHttpUtil.getFriends(mCustomerInfoEntity, SOURCETYPE, this);
	}


	/**
	 * 点击按钮
	 * 
	 * @param box
	 */
	void checkId(CheckBox box) {
		allCheckBtn.setChecked(false);
		activeCheckBtn.setChecked(false);
		recentlyCheckBtn.setChecked(false);
		nearbyBtn.setChecked(false);
		box.setChecked(true);
		isCheckedBox = box;
		allCheckBtn.setTextColor(getResources().getColor(R.color.tab_txt_gray));
		activeCheckBtn.setTextColor(getResources().getColor(R.color.tab_txt_gray));
		recentlyCheckBtn.setTextColor(getResources().getColor(R.color.tab_txt_gray));
		nearbyBtn.setTextColor(getResources().getColor(R.color.tab_txt_gray));
		box.setTextColor(getResources().getColor(R.color.tab_txt_orange));
	}

}
